package Solution.problem055;

/**
 * @program Leetcode
 * @description:
 * @author: lishangsheng
 * @create: 2019/05/29 19:18
 */
public class Solution {
    private static boolean canJump(int[] nums) {
        if(nums.length<1)
            return false;
        if(nums.length==1)
            return true;

        int max=0;
        //记录到当前点时能到达的最大位置
        for(int i=0;i<nums.length-1;i++){
            max=Math.max(max, i+nums[i]);
            if(max<i+1){
                //如果到达不了后续点(这里通常情况为 当前点为0，前面的能达到的最大点 为当前点或者当前点前面的点)，返回false
                return false;
            }
            if(max>=(nums.length-1)){
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        int[] array = new int[]{2, 3, 1, 1, 4};
        System.out.println(canJump(array));
        int[] array2 = new int[]{3, 2, 1, 0, 4};
        System.out.println(canJump(array2));
        int[] array3 = new int[]{3, 3, 1, 0, 4};
        System.out.println(canJump(array3));
        int[] array4 = new int[]{3, 5, 1, 1, 0};
        System.out.println(canJump(array4));
        int[] array5 = new int[]{0, 5, 1, 1, 0};
        System.out.println(canJump(array5));

    }
    private static boolean canJump2(int[] nums) {
        if (nums == null || nums.length <= 1) {
            return true;
        }
        int max=0;
        for(int i=0;i<nums.length;i++){
            max=Math.max(max,i+nums[i]);
            /*中途到达结尾*/
            if(max>=nums.length-1){
                return true;
            }
            /*到不了下一步*/
            if(max<i+1){
                return false;
            }
        }
        return false;
    }

    private static int getMax(int index, int[] nums) {
        int max = index + 1;
        for (int i = index; i < nums.length; ) {

            if (nums[i] == 0) {
                return i + 1;
            }
            if (nums[i] + i + 1 > nums.length) {
                return nums[i] + i + 1;
            }

            i = i + nums[i];
            max = i + 1;
        }

        return max;
    }

}
